package com.qf.fmall2302.shopcart.controller;

import com.qf.fmall2302.shopcart.entity.ShoppingCart;
import com.qf.fmall2302.shopcart.service.IShoppingCartService;
import com.qf.fmall2302.utils.FmallConstants;
import com.qf.fmall2302.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 购物车  前端控制器
 * </p>
 *
 * @author dongjl
 * @since 2023-08-24
 */
@RestController
@RequestMapping("/shopcart")
@Slf4j
@CrossOrigin
public class ShoppingCartController {

    @Autowired
    IShoppingCartService shoppingCartService;

    @GetMapping("/listbycids")
    public ResultVo listbycids(Integer[] cids){

        log.info("入参为,cids={}", Arrays.asList(cids));

        List<ShoppingCart> data = shoppingCartService.listByCids(cids);

        return ResultVo.ok(FmallConstants.SUCCESS_CODE, FmallConstants.SUCCESS_MSG, data);
    }


    @PutMapping("/update/{cid}/{num}")
    public ResultVo update(@PathVariable("cid") Integer cid,@PathVariable("num") Integer num){

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setCartId(cid);
        shoppingCart.setCartNum(num+"");
        shoppingCartService.updateById(shoppingCart);

        return ResultVo.ok(FmallConstants.SUCCESS_CODE, FmallConstants.SUCCESS_MSG, null);
    }

    @GetMapping("/list")
    public ResultVo list(Integer userId){
        log.info("入参为:userId={}",userId);
        List<ShoppingCart> data = shoppingCartService.listbyUserId(userId);
        return ResultVo.ok(FmallConstants.SUCCESS_CODE, FmallConstants.SUCCESS_MSG, data);
    }


    @PostMapping("/add")
    public ResultVo add(@RequestBody ShoppingCart shoppingCart){
        log.info("入参为:shoppingCart={}",shoppingCart);

        // 如果shoppingCart对象中的 productid带有#了，去掉#
        String productId = shoppingCart.getProductId();
        if (productId.contains("#")){
            productId = productId.replaceAll("#", "");
        }

        shoppingCart.setProductId(productId);


        shoppingCartService.add(shoppingCart);

        return ResultVo.ok(FmallConstants.SUCCESS_CODE, FmallConstants.SUCCESS_MSG, null);

    }

}
